<template>
  <view class="page-container">
    <!-- 顶部导航栏 -->
    <uni-nav-bar
      :border="false"
      title="账户余额"
      fixed
      left-icon="back"
      @clickLeft="goBack"
    />

    <!-- 固定内容区域 -->
    <view class="fixed-content">
      <!-- 顶部提示 -->
      <view class="top-notice">
        <uni-icons type="info-filled" size="16" color="#FF9500"></uni-icons>
        <text class="notice-text">每日收益会在当日 23:00:00自动提</text>
      </view>

      <!-- 资产概览 -->
      <view class="asset-overview">
        <view class="asset-header-row">
          <text class="asset-label">总资产(元)</text>
          <view class="merchant-tag" @click="showMerchantSelector">
            <text class="merchant-name">{{ currentMerchant.name }}</text>
            <view v-if="currentMerchant.status === 'active'" class="status-tag">
              使用中
            </view>
            <uni-icons type="down" size="12" color="#333"></uni-icons>
          </view>
        </view>
        <text v-if="overviewLoading" class="asset-value">加载中...</text>
        <text v-else class="asset-value">{{ assetData.totalAsset }}</text>
        <text class="yesterday-income">
          昨日收益
          <text v-if="overviewLoading">加载中...</text>
          <text v-else>{{ assetData.yesterdayIncome }}</text>
        </text>
      </view>

      <!-- 资金明细 -->
      <view class="fund-details">
        <view class="fund-item">
          <view class="fund-label-row">
            <uni-icons type="info-filled" size="14" color="#FFB200"></uni-icons>
            <text class="fund-label">可结算资金</text>
          </view>
          <text class="fund-value">{{ assetData.settleFund }}</text>
        </view>
        <view class="fund-item clickable" @click="goToRefundReserve">
          <view class="fund-label-row with-arrow">
            <text class="fund-label">退款备用金</text>
            <uni-icons type="right" size="14" color="#999"></uni-icons>
          </view>
          <text class="fund-value">{{ assetData.refundReserve }}</text>
        </view>
        <view class="fund-item">
          <text class="fund-label">提现中</text>
          <text class="fund-value">{{ assetData.withdrawing }}</text>
        </view>
      </view>

      <!-- 账户选项 -->
      <view class="account-options">
        <view class="account-option" @click="handleBankAccount">
          <text>结算银行账户</text>
          <view>
            <text>对私账户</text>
            <uni-icons type="right" size="16" color="#999"></uni-icons
          ></view>
        </view>
      </view>

      <!-- 筛选栏 -->
      <view class="filter-bar">
        <view class="date-selector" @click="showDatePicker">
          <text class="date-text">{{ currentDateText }}</text>
          <uni-icons type="down" size="16" color="#333"></uni-icons>
        </view>
        <view class="filter-btn" @click="showFilterModal">
          <text>筛选</text>
          <uni-icons type="filter" size="16" color="#666"></uni-icons>
        </view>
      </view>
    </view>

    <!-- 可滚动的交易列表 -->
    <scroll-view
      class="transaction-list"
      scroll-y
      :style="{ height: scrollHeight }"
      @scrolltolower="handleLoadMore"
    >
      <view
        v-for="item in transactionList"
        :key="item.id"
        class="transaction-item"
        @click="handleTransactionClick(item)"
      >
        <view class="transaction-info">
          <text class="transaction-type">{{ item.type }}</text>
          <text class="transaction-time">{{ item.time }}</text>
        </view>
        <view class="transaction-right">
          <view class="amount-info">
            <text
              class="transaction-amount"
              :class="{ positive: item.amount > 0 }"
            >
              {{ item.amount > 0 ? "+" : "" }}{{ item.amount.toFixed(2) }}
            </text>
            <text v-if="item.balance !== undefined" class="transaction-balance">
              余额 {{ item.balance }}
            </text>
          </view>
          <uni-icons type="right" size="16" color="#999"></uni-icons>
        </view>
      </view>

      <!-- 加载中状态（首次加载） -->
      <view
        v-if="listLoading && transactionList.length === 0"
        class="loading-state"
      >
        <uni-load-more status="loading" />
      </view>

      <!-- 空状态 -->
      <view
        v-if="!listLoading && transactionList.length === 0"
        class="empty-state"
      >
        <text>暂无交易记录</text>
      </view>

      <!-- 触底加载更多 -->
      <LoadMore
        v-if="transactionList.length > 0"
        :status="loadMoreStatus"
        @retry="handleLoadMore"
      />
    </scroll-view>

    <!-- 日期选择弹窗 -->
    <DatePicker
      ref="datePickerRef"
      :current-year="currentDate.year"
      :current-month="currentDate.month"
      @confirm="handleDateConfirm"
    />

    <!-- 筛选弹窗 -->
    <FilterModal ref="filterModalRef" @confirm="handleFilterConfirm" />

    <!-- 商户选择弹窗 -->
    <MerchantSelector
      ref="merchantSelectorRef"
      @select="handleMerchantSelect"
    />
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useRequest } from "ahooks-vue";
import { useStoreStore } from "@/store/modules/store";
import { useUserStore } from "@/store/modules/user";
import { getMerchantBalanceDetail, getAccountOverview } from "@/api/mine";
import { dateUtils } from "@/utils/dayjs";
import DatePicker from "./components/DatePicker.vue";
import FilterModal from "./components/FilterModal.vue";
import MerchantSelector from "./components/MerchantSelector.vue";
import LoadMore from "@/components/common/LoadMore/LoadMore.vue";

// 使用 Pinia store
const storeStore = useStoreStore();
const userStore = useUserStore();

// 资产数据
const assetData = ref({
  totalAsset: "0.00",
  yesterdayIncome: "0.00",
  settleFund: "0.00",
  refundReserve: "0.00",
  withdrawing: "0.00",
});

// 获取账户总览
const { loading: overviewLoading, run: fetchAccountOverview } = useRequest(
  () =>
    getAccountOverview({
      merchantId: storeStore.storeId,
      userId: userStore.userInfo?.userId,
    }),
  {
    manual: true,
    onSuccess: (response) => {
      console.log("账户总览数据：", response);
      if (response?.data) {
        assetData.value.totalAsset = response.data.a?.toFixed(2) || "0.00";
        assetData.value.yesterdayIncome = response.data.b?.toFixed(2) || "0.00";
      }
    },
    onError: (error) => {
      console.error("获取账户总览失败：", error);
      uni.showToast({
        title: "获取账户信息失败",
        icon: "none",
      });
    },
  },
);

// 当前选中的日期
const currentDate = ref({
  year: 2025,
  month: 10,
});

// 日期文本显示
const currentDateText = computed(() => {
  return `${currentDate.value.year}-${currentDate.value.month}月`;
});

// 日期选择器引用
const datePickerRef = ref(null);

// 筛选弹窗引用
const filterModalRef = ref(null);

// 商户选择器引用
const merchantSelectorRef = ref(null);

// 当前选中的商户
const currentMerchant = ref({
  id: 1,
  name: "中金子商户",
  status: "active",
});

// 已选中的标签
const selectedTags = ref([]);

// 交易列表
const transactionList = ref([]);

// 分页参数
const pageParams = ref({
  offset: 1,
  limit: 20,
});

// 是否有更多数据
const hasMore = ref(true);

// 加载更多状态：loading-加载中, nomore-没有更多, error-加载失败, more-可以加载更多
const loadMoreStatus = computed(() => {
  if (listLoading.value) return "loading";
  if (!hasMore.value) return "nomore";
  return "more";
});

// 获取余额明细接口
const { loading: listLoading, run: fetchBalanceDetail } = useRequest(
  (params) =>
    getMerchantBalanceDetail({
      merchantId: storeStore.storeId,
      userId: userStore.userInfo?.userId,
      selectTime: `${currentDate.value.year}-${String(
        currentDate.value.month,
      ).padStart(2, "0")}`,
      ...params,
    }),
  {
    manual: true,
    onSuccess: (response) => {
      console.log("获取余额明细成功：", response);
      if (response?.data?.rows && Array.isArray(response.data.rows)) {
        const newData = response.data.rows.map((item, index) => ({
          id: `${pageParams.value.offset}-${index}`,
          type: item.context || "未知交易",
          time: dateUtils.formatTimestamp(item.time), // 使用 dayjs 工具格式化时间戳
          amount:
            item.status === 1 ? Math.abs(item.money) : -Math.abs(item.money),
          // 后端可能不返回余额，这里暂时不显示
        }));

        // 如果是第一页，直接赋值；否则追加
        if (pageParams.value.offset === 1) {
          transactionList.value = newData;
        } else {
          transactionList.value = [...transactionList.value, ...newData];
        }

        // 根据 total 判断是否还有更多数据
        const total = response.data.total || 0;
        const currentTotal = pageParams.value.offset * pageParams.value.limit;
        hasMore.value = currentTotal < total;
      } else {
        if (pageParams.value.offset === 1) {
          transactionList.value = [];
        }
        hasMore.value = false;
      }
    },
    onError: (error) => {
      console.error("获取余额明细失败：", error);
      uni.showToast({
        title: "获取明细失败",
        icon: "none",
      });
    },
  },
);

// 初始化加载
const initLoad = () => {
  pageParams.value.offset = 1;
  hasMore.value = true;
  fetchBalanceDetail(pageParams.value);
};

// 加载更多
const handleLoadMore = () => {
  if (listLoading.value || !hasMore.value) return;

  pageParams.value.offset += 1;
  fetchBalanceDetail(pageParams.value);
};

// 计算滚动区域高度
const scrollHeight = computed(() => {
  // 88rpx 导航栏 + 固定内容区域高度 (顶部提示60rpx + 资产概览200rpx + 资金明细140rpx + 账户按钮100rpx + 筛选栏80rpx + 间距60rpx)
  return "calc(100vh - 160 - 640rpx)";
});

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 显示日期选择器
const showDatePicker = () => {
  datePickerRef.value.open();
};

// 确认日期选择
const handleDateConfirm = (date) => {
  currentDate.value = date;
  console.log("选择日期:", currentDate.value);
  // 根据日期重新加载数据
  initLoad();
};

// 显示筛选弹窗
const showFilterModal = () => {
  filterModalRef.value.open();
};

// 确认筛选
const handleFilterConfirm = (filterData) => {
  selectedTags.value = filterData.tags;
  console.log("筛选条件:", filterData);

  const typeText = filterData.type === "income" ? "收入" : "支出";
  const tagCount = filterData.tags.length;

  uni.showToast({
    title: tagCount > 0 ? `已筛选 ${typeText} ${tagCount} 项` : "已清空筛选",
    icon: "none",
  });

  // 根据筛选条件重新加载数据
  initLoad();
};

// 处理银行账户点击
const handleBankAccount = () => {
  uni.navigateTo({
    url: "/pages/mine/balance/settlementAccount",
  });
};

// 处理对私账户点击
const handlePrivateAccount = () => {
  uni.showToast({
    title: "对私账户",
    icon: "none",
  });
};

// 显示商户选择器
const showMerchantSelector = () => {
  merchantSelectorRef.value.open(currentMerchant.value.id);
};

// 处理商户选择
const handleMerchantSelect = (merchant) => {
  currentMerchant.value = merchant;
  console.log("选择商户:", merchant);

  uni.showToast({
    title: `已切换至 ${merchant.name}`,
    icon: "none",
  });

  // 根据选择的商户重新加载数据
  initLoad();
};

// 跳转到退款备用金页面
const goToRefundReserve = () => {
  uni.navigateTo({
    url: "/pages/mine/balance/refundReserve",
  });
};

// 处理交易项点击
const handleTransactionClick = (item) => {
  console.log("点击交易:", item);
  uni.navigateTo({
    url: `/pages/mine/balance/transactionDetail?id=${item.id}`,
  });
};

onMounted(() => {
  console.log("账户余额页面加载完成");

  // 从本地缓存恢复店铺和用户信息
  storeStore.hydrateFromStorage();
  userStore.hydrateFromStorage();

  console.log("店铺信息：", {
    merchantId: storeStore.storeId,
    merchantName: storeStore.merchantName,
  });
  console.log("用户信息：", userStore.userInfo);

  // 获取账户总览数据
  if (storeStore.storeId && userStore.userInfo?.userId) {
    fetchAccountOverview();
    // 初始化加载余额明细
    initLoad();
  } else {
    console.warn("缺少 merchantId 或 userId，无法获取账户信息");
  }
});
</script>

<style lang="scss" scoped>
.page-container {
  // display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  //height: 100vh;
  background-color: #f5f5f5;
}

.fixed-content {
  background-color: #f5f5f5;
  width: 100%;
}

// 顶部提示
.top-notice {
  display: flex;
  align-items: center;
  gap: 8rpx;
  background-color: #fff8e6;
  padding: 16rpx 30rpx;
  margin-bottom: 20rpx;
  border-radius: 8rpx;
}

.notice-text {
  font-size: 24rpx;
  color: #ff9500;
}

// 资产概览
.asset-overview {
  background-color: #fff;
  padding: 30rpx;
  margin: 0 30rpx 20rpx;
  border-radius: 12rpx;
}

.asset-header-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.asset-label {
  font-size: 28rpx;
  color: #666;
}

.merchant-tag {
  display: flex;
  align-items: center;
  gap: 8rpx;
  cursor: pointer;

  &:active {
    opacity: 0.7;
  }
}

.merchant-name {
  font-size: 26rpx;
  color: #333;
}

.status-tag {
  background-color: #00c48c;
  padding: 8rpx 12rpx;
  border-radius: 6rpx;
  font-size: 22rpx;
  color: #fff;
}

.asset-value {
  font-size: 80rpx;
  font-weight: 700;
  color: #333;
  line-height: 1.2;
  margin-bottom: 12rpx;
}

.yesterday-income {
  font-size: 24rpx;
  color: #999;
}

// 资金明细
.fund-details {
  background-color: #fff;
  padding: 20rpx 30rpx;
  margin: 0 30rpx 20rpx;
  border-radius: 12rpx;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.fund-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 16rpx;

  &.clickable {
    cursor: pointer;

    &:active {
      opacity: 0.7;
    }
  }
}

.fund-label-row {
  display: flex;
  align-items: center;
  gap: 4rpx;
}

.fund-label {
  font-size: 24rpx;
  color: #666;
}

.fund-value {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
}

// 账户选项
.account-options {
  background-color: #fff;
  margin: 0 30rpx 20rpx;
  border-radius: 12rpx;
  overflow: hidden;
}

.account-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx 30rpx;
  font-size: 28rpx;
  color: #333;
  border-bottom: 1rpx solid #f0f0f0;

  &:last-child {
    border-bottom: none;
  }

  &:active {
    background-color: #f9f9f9;
  }
}

// 筛选栏
.filter-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
  padding: 20rpx 30rpx;
  margin: 0 30rpx;
  border-radius: 12rpx 12rpx 0 0;
}

.date-selector {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.date-text {
  font-size: 28rpx;
  font-weight: 500;
  color: #333;
}

.filter-btn {
  display: flex;
  align-items: center;
  gap: 8rpx;
  font-size: 26rpx;
  color: #666;
}

// 交易列表
.transaction-list {
  // margin-top: 700rpx;
  background-color: #fff;
  margin-left: 30rpx;
  margin-right: 30rpx;
  margin-bottom: 20rpx;
  border-radius: 12rpx;
  overflow: hidden;
  border-radius: 0 0 12rpx 12rpx;
  width: calc(100% - 60rpx);
}

.transaction-item {
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx 30rpx;
  border-bottom: 1rpx solid #f0f0f0;

  &:last-child {
    border-bottom: none;
  }

  &:active {
    background-color: #f9f9f9;
  }
}

.transaction-info {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.transaction-type {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.transaction-time {
  font-size: 24rpx;
  color: #999;
}

.transaction-amount-wrapper {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.transaction-amount {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;

  &.positive {
    color: #ff4d4f;
  }
}

.transaction-balance {
  font-size: 22rpx;
  color: #999;
}

.loading-state {
  display: flex;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
  font-size: 28rpx;
  color: #999;
}

.transaction-right {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 12rpx;
}
.amount-info {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  justify-content: center;
}
</style>
